import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import './home.less'
import {Carousel, WingBlank, Grid, ListView} from 'antd-mobile';
import {NavLink} from 'react-router-dom'
import {queryIndexEntry, restaurants} from '@/api/api'

let pageIndex = 0;

class Home extends Component {
    constructor(props) {
        super(props);
        const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
        const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];
        const dataSource = new ListView.DataSource({
            getRowData,
            getSectionHeaderData: getSectionData,
            rowHasChanged: (row1, row2) => row1 !== row2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
        });
        this.state = {
            data: ['1', '2', '3', '4'],
            slideIndex: 2,
            items: [],
            lists: [],
            isLogin: false,
            dataSource,
            isLoading: true,
            height: 3.48
        };
    }

    componentDidMount() {
        this.initData();
    }

    componentDidUpdate() {
        if (this.state.slideIndex !== this.state.data.length - 1) {
            this.setState({slideIndex: this.state.data.length - 1});
        }
    }

    // 初始化数据
    initData = async () => {
        try {
            const entry = await queryIndexEntry();
            const list = await restaurants({
                latitude: 31.22967,
                longitude: 121.4762
            });
            this.rData = list;
            this.setState({
                items: Array.from(entry).map((item) => ({
                    icon: `https://fuss10.elemecdn.com${item.image_url}`,
                    text: item.title,
                })),
                lists: list,
                dataSource: this.state.dataSource.cloneWithRows(this.rData),
                isLoading: false
            });
        } catch (err) {
            console.error(err);
        }
    };
    onEndReached = async (event) => {
        // load new data
        // hasMore: from backend data, indicates whether it is the last page, here is false
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        const list = await restaurants({
            latitude: 31.22967,
            longitude: 121.4762,
            offset: 20 * (++pageIndex)
        });
        this.rData = this.rData.concat(list);
        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(this.rData),
            isLoading: false
        });
    }

    render() {
        let index = this.state.lists.length - 1;
        const row = (rowData, sectionID, rowID) => {
            if (index < 0) {
                index = this.state.lists.length - 1;
            }
            const obj = this.state.lists[index--];
            return (
                <div className="list-content">
                    <div className="optimalLeft">
                        <img src={`https://elm.cangdu.org/img/${obj.image_path}`} alt=""/>
                    </div>
                    <ul className="optimalRight">
                        <li className="rightTop">
                            {obj.name}
                            <span className="distance">{obj.distance}</span>
                        </li>
                        <li className="rightMiddle">
                        <span className="first-score">
                            *****
                        </span>
                            <span>4</span>
                            <span style={{marginLeft: '4px'}}>月销{obj.rating_count}单</span>
                            <span style={{float: 'right'}}>{obj.order_lead_time}分钟</span>
                        </li>
                        <li className="rightBottom">
                            <span>起送{obj.float_minimum_order_amount}元</span>
                            <span className="stand"></span>
                            <span>配送费约¥{obj.float_delivery_fee}</span>
                            <span className="bottomTag">
                            <span className="tagLeft">蜂鸟专送</span>
                            <span className="tagRight">准时达</span>
                        </span>
                        </li>
                        <li className="activity">新用户立减</li>
                    </ul>
                </div>
            );
        };
        return (
            <div className="home-container">
                <header className="header">
                    <span className="floatLeft">广东省深圳市南山区科苑路</span>
                    {this.state.isLogin ? (<span className="floatRight"> 李海</span>) : (
                        <NavLink to="/login"><span className="floatRight"
                                                   onClick={this.loginIn}> 登录|注册</span></NavLink>)}
                </header>
                <WingBlank style={{margin: 0}}>
                    <Carousel
                        autoplay={true}
                        infinite
                        selectedIndex={this.state.slideIndex}>
                        {this.state.data.map((val, index) => (
                            <img key={val} src={`https://ganks.oss-cn-shenzhen.aliyuncs.com/img/banner${val}.jpg`}
                                 alt=""
                                 style={{width: '100%', verticalAlign: 'top'}}
                            />
                        ))}
                    </Carousel>
                </WingBlank>
                <Grid data={this.state.items} isCarousel hasLine={false} onClick={_el => console.log(_el)}/>
                <section id="myOverFlow">
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderHeader={() => <p className="nearbyShops">附件商家</p>}
                        renderFooter={() => (<div style={{padding: 5, textAlign: 'center'}}>
                            {!this.state.isLoading ? 'Loading...' : 'Loaded'}
                        </div>)}
                        renderRow={row}
                        style={{
                            height: '100vh',
                            overflow: 'auto',
                        }}
                        pageSize={20}
                        onScroll={() => {

                        }}
                        scrollRenderAheadDistance={500}
                        onEndReached={this.onEndReached}
                        onEndReachedThreshold={10}
                    />
                </section>
            </div>);
    }
}

export default Home;
